using Aliyun.Credentials.Models;
using Vin.Extension.Alibaba.Options;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.AspNetCore.Singleton;

namespace Vin.Extension.Alibaba.Services;

public abstract class AlibabaBaseService<T> : VinBaseService where T : AlibabaCloud.OpenApiClient.Client
{
    public abstract string Endpoint { get; }

    public AlibabaOption AlibabaOption => VinApp.GetOption<AlibabaOption>();

    public T AccessClient
    {
        get
        {
            var credential = new Aliyun.Credentials.Client(new Config()
            {
                Type = "access_key",
                AccessKeyId = AlibabaOption.AccessKeyId,
                AccessKeySecret = AlibabaOption.AccessKeySecret,
            });
            
            //  as dynamic
            var config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                Credential = credential,
            };
            if (string.IsNullOrEmpty(Endpoint))
                throw new ArgumentNullException(nameof(Endpoint), "Endpoint cannot be null or empty.");
            config.Endpoint = Endpoint;
            return Activator.CreateInstance(typeof(T), config) as T ?? throw new InvalidOperationException();
        }
    }
}